package com.sgb.kjwl.view.ui.fragment;

import android.Manifest;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.text.style.ScaleXSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.gyf.barlibrary.ImmersionBar;
import com.im.immodel.IMUtils;
import com.sgb.businessmodule.view.ui.activity.BusinessOpportunityHallActivity;
import com.sgb.businessmodule.view.ui.adapter.AdapterJumpPush;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.ui.activity.AccountActivity;
import com.sgb.capital.view.ui.activity.AsiaRecordActivity;
import com.sgb.capital.view.ui.activity.BusinessManagementActivity;
import com.sgb.capital.view.ui.activity.CertificatedCompanyActivity;
import com.sgb.capital.view.ui.activity.CertificatedUserActivity;
import com.sgb.capital.view.ui.activity.CompanyBankCardsActivity;
import com.sgb.capital.view.ui.activity.FinanceFlowAndCostQueryActivity;
import com.sgb.capital.view.ui.activity.OpenAccountFirstActivity;
import com.sgb.capital.view.ui.activity.PayActivity;
import com.sgb.capital.view.ui.activity.PersonBankCardsActivity;
import com.sgb.capital.view.ui.activity.ReimburseActivity;
import com.sgb.capital.view.ui.activity.TransferAccountsActivity;
import com.sgb.capital.view.ui.activity.WithdrawalBalanceActivity;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentSelf5Binding;
import com.sgb.kjwl.databinding.ItemFooterSelfBusinessOpportunityBinding;
import com.sgb.kjwl.databinding.ItemFooterSelfDynamicBinding;
import com.sgb.kjwl.databinding.ItemHeaderSelfBinding;
import com.sgb.kjwl.databinding.ItemSelfMenuBinding;
import com.sgb.kjwl.databinding.ItemWebsiteTabFirstBinding;
import com.sgb.kjwl.di.self.DaggerSelfFragComponent;
import com.sgb.kjwl.di.self.SelfFragModule;
import com.sgb.kjwl.model.entity.CapitalEntity;
import com.sgb.kjwl.model.entity.H5MsgEntity;
import com.sgb.kjwl.model.entity.self.SecondMore;
import com.sgb.kjwl.pop.CompanyChangeDialog;
import com.sgb.kjwl.view.ui.activity.self.mine.SecondMoreActivity;
import com.sgb.link.entity.PickFilterEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.businessmanagement.CompanyEntity;
import com.sgb.kjwl.model.entity.self.ApplyCount;
import com.sgb.kjwl.model.entity.self.ManagementDynamicEntity;
import com.sgb.kjwl.model.entity.self.PermissionMenuEntity;
import com.sgb.kjwl.model.entity.self.SecondMore;
import com.sgb.kjwl.model.entity.self.TotalUnReadMsgEntity;
import com.sgb.kjwl.model.entity.user.EssentiaIinformationeEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.MineAdapterItemClick;
import com.sgb.kjwl.view.event.CustomViewsInfo;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.event.MainEvent;
import com.sgb.kjwl.view.event.WebEvent;
import com.sgb.kjwl.view.event.self.AuthenticationEvent;
import com.sgb.kjwl.view.event.self.LogoRefreshEvent;
import com.sgb.kjwl.view.event.self.RefreshUnReadNumEvent;
import com.sgb.kjwl.view.event.self.UploadAvatarEvent;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.ScanActivity;
import com.sgb.kjwl.view.ui.activity.manage.AgentApplyActivity;
import com.sgb.kjwl.view.ui.activity.manage.AgentTotalOrderActivity;
import com.sgb.kjwl.view.ui.activity.manage.WebSiteInquiryActivity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.activity.manage.business.SubscribeBusinessActivity;
import com.sgb.kjwl.view.ui.activity.manage.special.SpecialMemberActivity;
import com.sgb.kjwl.view.ui.activity.self.JoinCompanyActivity;
import com.sgb.kjwl.view.ui.activity.self.PersonInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.SelfQrCodeActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity3;
import com.sgb.kjwl.view.ui.activity.self.authentication.CertificationActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.OrganizationAuthActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.TeamAuthActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.UserAuthDetailActivity;
import com.sgb.kjwl.view.ui.activity.self.company.AgentCentralizedMiningActivity;
import com.sgb.kjwl.view.ui.activity.self.company.AgentEnquiryActivity;
import com.sgb.kjwl.view.ui.activity.self.company.ManagementDynamicActivity;
import com.sgb.kjwl.view.ui.activity.self.company.QuotationActivity;
import com.sgb.kjwl.view.ui.activity.self.company.RegistrationActivity;
import com.sgb.kjwl.view.ui.activity.self.mine.MangermoreActivity;
import com.sgb.kjwl.view.ui.activity.self.mine.SecondMoreActivity;
import com.sgb.kjwl.view.ui.activity.self.publish.SettingActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.RegisterActivity3;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.activity.vehicleManagement.AddDriverInfoActivity;
import com.sgb.kjwl.view.ui.activity.vehicleManagement.DriverInfoActivity;
import com.sgb.kjwl.view.ui.adapter.self.SelfBusinessOpportunityAdapter;
import com.sgb.kjwl.view.ui.adapter.self.SelfFirstOrderNestingAdapter;
import com.sgb.kjwl.view.ui.adapter.self.SelfSecondOrderNestingAdapter;
import com.sgb.kjwl.view.ui.fragment.self.company.ManagementDynamicFragment;
import com.sgb.kjwl.view.widget.SelfPopWindow;
import com.sgb.kjwl.view.widget.manage.CenterImageSpan;
import com.sgb.kjwl.view.widget.self.MenuClickUtils;
import com.sgb.kjwl.view.widget.self.permission.BasePermissionCallBack;
import com.sgb.kjwl.view.widget.self.permission.UserPermissionUtils;
import com.sgb.kjwl.viewmodel.self.SelfFragModel5;
import com.sgb.link.utils.SizeUtils;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.LoginTokenEvent;
import com.swgk.core.event.MessageEvent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.ACAdminDialogUtils;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.LiuHaiPingUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.UserOperating;
import com.swgk.core.xrecyclerview.AppBarStateChangeListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import static android.app.Activity.RESULT_OK;


/**
 * Description:
 * Author zhengkewen* Time
 */
public class SelfFragment5 extends AppLazyFragment {
    public static int MANGER = 10086;//排序常量标识
    public static int SECONDMORE = 10087;//二级菜单编辑标识
    private FragmentSelf5Binding binding;
    private CompanyChangeDialog companyChangePop;
    private List<CompanyEntity> companyList = new ArrayList<>();
    private SelfPopWindow selfPopWindow;
    private boolean flag;

    private boolean isExpanded;//appbar当前的状态
    @Inject
    SelfFragModel5 viewModel;
    private MainActivity activity;

    private String comNo; //缓存当前状态下的no
    //初始化企业角色为未认证（0为已认证）
    private int companyRole = 3;
    private int enterpriseAuth;
    public String personal_portrait;
    private List<PermissionMenuEntity> dataList = new ArrayList<>();


    private List<PermissionMenuEntity.ListEntity> reallyDataList = new ArrayList<>();//新个人中心暂时只展示一条
    //用户基本信息
    private EssentiaIinformationeEntity UserEntity = new EssentiaIinformationeEntity();
    public boolean isLoginJump;
    private SelfFirstOrderNestingAdapter firstOrderNestingAdapter;
    private boolean isFirst;
    private Map<String, String> userData = new HashMap<>();
    private int mType;//表示当前是企业1 个人0 团队2 组织3
    private List<CustomViewsInfo> customViewsInfoList = new ArrayList<>();// 用户认证
    private UserMsgEntity userEntity;// 用户认证信息
    private int mProcess;
    private boolean mIsUser;
    private H5MsgEntity mBank;
    private String mBalance = "0.00";
    private RecyclerView mHeadCompanyRecyclerView;
    private String companyNo = "";
    private RecyclerView mNoAuthRecyclerView; //未认证的时候添加
    private SelfSecondOrderNestingAdapter mNoAuthHeadAdapter;
    private SelfSecondOrderNestingAdapter mHeadCompanyAdapter;
    private int mangertype = -1;

    List<PermissionMenuEntity.ListEntity> listHeadCompany = new ArrayList<>();//企业头部代办

    private ItemFooterSelfBusinessOpportunityBinding mFooterBinding; //商机
    private SelfBusinessOpportunityAdapter mBusinessAdapter;
    private BusinessTypeAdapter mBusinessTypeAdapter;
    private String mBusinessType = "0";

    private ItemFooterSelfDynamicBinding mDynamicBinding;//经营动态
    private ManagementDynamicFragment.DynamicAdapter mDynamicAdapter;
    private ItemHeaderSelfBinding mHeaderBinding;//头部

    private SelfMenuAdapter mMenuAdapter;

    //订单的权限
    private ArrayList<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>> mMenus = new ArrayList<>();
    private List<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>> mTempMenus = new ArrayList<>();

    //申请的权限
    private ArrayList<PickFilterEntity<Object>> mApplyMenus = new ArrayList<>();

    //员工审核
    private ArrayList<PickFilterEntity<Object>> mStaffCheckMenus = new ArrayList<>();
    //客户审核
    private ArrayList<PickFilterEntity<Object>> mCustomerCheckMenus = new ArrayList<>();

    //代办集采
    private List<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>> mAgentCentralizedMiningMenus = new ArrayList<>();

    private ArrayList<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>> mReallyAgentCentralizedMiningMenus = new ArrayList<>();

    private List<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>> mTempAgentCentralizedMiningMenus = new ArrayList<>();


    private int lastPosition = -1; //用于判断recyclerView滑动的时候 是不是同一个item的位置
    private int mTabPosition = -1; //点击的tab的position、
    private boolean isRecyclerViewScroll; //是否是recycleView自己的滚动
    private boolean mPersonAuth; //用户是否认证
    private boolean mIsH5Login = false;

    public boolean isEnableClick = false; //是否可以点击头部

    //是否有权限进入付款页面
    private boolean goToPayEnable = false;

    //是否有询价商品的权限
    private boolean permissionEnquiryShop = false;

    private boolean isFirstRefresh = true;

    private int mChangeHeight = 0;//适配

    private String mInquiryNum = "";

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof MainActivity) {
            activity = (MainActivity) context;
        }
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerSelfFragComponent.builder()
                .appComponent(appComponent)
                .selfFragModule(new SelfFragModule(this))
                .build()
                .inject(this);
    }

    //创建视图
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //绑定view和Activity
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_self5, container, false);
        binding.liuhaiStatusView2.getLayoutParams().height = LiuHaiPingUtils.getStatusBarHeight(getActivity());
        return binding.getRoot();

    }

    /**
     * 初始化
     */
    @SuppressLint("NewApi")
    @Override
    protected void initView() {
        //判断EvEntBus是否存在
        if (!EventBus.getDefault().isRegistered(this)) {
            //注册EvEntBus
            EventBus.getDefault().register(this);
        }
        //给控件设置点击事件
        initClickView();
        //创建个人中心的popuwindw的弹窗
        initPopWindow();
        //主UI样式初始化
        initWindow();

        //初始化企业头部代办的recycle
        initHeadCompanyRecycle();
        //初始化菜单
        initRecyclerview();

        initLiveData();

        getHeight();

        initHeaderRecycle();

        binding.smartRefreshLayout.setEnableLoadMore(false);
        binding.smartRefreshLayout.setEnableRefresh(true);
        binding.smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            if (isFirstRefresh) {
                isFirstRefresh = false;
                return;
            }
            refreshLayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "")) &&
                    !TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                //如果是已登录状态 手机缓存中没有保存任何公司信息
                isLoginJump = true;
            }
            getData();
        });
    }

    //初始化菜单适配器
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initHeaderRecycle() {
        if (mMenuAdapter == null) {
            mMenuAdapter = new SelfMenuAdapter(R.layout.item_self_menu);
        }
        mMenuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<PermissionMenuEntity> data = mMenuAdapter.getData();
                if (data != null && !data.isEmpty()) {
                    if (activity != null) {
                        activity.showMinePublishDialog(false, data.get(position).getName());
                    }
                    if (data.get(position).isChoose()) {
                        return;
                    }
                    for (int i = 0; i < data.size(); i++) {
                        if (position == i) {
                            data.get(position).setChoose(true);
                            reallyDataList.clear();
                            if (dataList.get(position) != null && data.get(position).getList() != null && !data.get(position).getList().isEmpty()) {
                                reallyDataList.addAll(data.get(position).getList());
                            }
                            tipPosition(0);
                            firstOrderNestingAdapter.setDatas(reallyDataList);
                            setCanNsEnable(position);
                            isShowFooter(mType, position == 0);
                            isShowHeader(position == 0);
                        } else {
                            data.get(i).setChoose(false);
                        }
                    }
                }
                mMenuAdapter.notifyDataSetChanged();
            }
        });
        binding.menuRecyclerview.setHasFixedSize(true);
        binding.menuRecyclerview.setAdapter(mMenuAdapter);
    }

    private void initLiveData() {
        viewModel.mManagementDynamicList.observe(this, managementDynamicEntities -> {
            mDynamicAdapter.setNewData(managementDynamicEntities.subList(0, Math.min(5, managementDynamicEntities.size())));
        });
        viewModel.businessList.observe(this, homeBusinessListEntities -> {
            if (mFooterBinding != null) {
                mFooterBinding.line.setVisibility(homeBusinessListEntities.isEmpty() ? View.GONE : View.VISIBLE);
            }
            mBusinessAdapter.setNewData(homeBusinessListEntities.subList(0, Math.min(5, homeBusinessListEntities.size())));

        });
        viewModel.businessTypeList.observe(this, pickFilterEntities -> {
            mBusinessTypeAdapter.setNewData(pickFilterEntities);
        });
    }

    private View getHeaderView() {
        mHeaderBinding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.item_header_self, binding.firstordernestingRecyclerview, false);
        initHeadCompanyRecycle();
        mHeaderBinding.getRoot().setVisibility(View.GONE);
        return mHeaderBinding.getRoot();
    }

    private View getDynamicRecycleView() {
        mDynamicBinding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.item_footer_self_dynamic, binding.firstordernestingRecyclerview, false);
        mDynamicBinding.dynamicRecyclerview.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
        mDynamicBinding.dynamicRecyclerview.setHasFixedSize(true);
        if (mDynamicAdapter == null) {
            mDynamicAdapter = new ManagementDynamicFragment.DynamicAdapter(requireContext(), R.layout.item_manage_dynamic);
            mDynamicAdapter.bindToRecyclerView(mDynamicBinding.dynamicRecyclerview);
        }
        View empty = LayoutInflater.from(getContext()).inflate(R.layout.layout_empty_view, mDynamicBinding.dynamicRecyclerview, false);
        mDynamicAdapter.setEmptyView(empty);
        mDynamicBinding.tvDynamicMore.setOnClickListener(v -> {
            ManagementDynamicActivity.Companion.launch(getContext());
        });
        mDynamicBinding.dynamicRecyclerview.addItemDecoration(
                new RecyclerCustomDecoration(
                        0f,
                        0f,
                        0f,
                        getResources().getDimension(R.dimen.dp1), getResources().getColor(R.color.color_main_bg)
                )
        );
        mDynamicAdapter.setCallBack(new ManagementDynamicFragment.DynamicAdapter.ClickCallback() {
            @Override
            public void clickName(@NotNull ManagementDynamicEntity item) {
                //去网站
                if (!TextUtils.isEmpty(item.getUserCompanyNo())) {
                    WebsiteInfoActivity.start(getContext(), item.getUserCompanyNo(), WebsiteInfoActivity.WEBSITE_FOR_COMPANY);
                } else if (!TextUtils.isEmpty(item.getUserNo())) {
                    WebsiteInfoActivity.start(getContext(), item.getUserNo(), WebsiteInfoActivity.WEBSITE_FOR_PERSONAL);
                }
            }

            @Override
            public void clickContent(@NotNull ManagementDynamicEntity item) {

            }
        });
        mDynamicBinding.getRoot().setVisibility(View.GONE);
        return mDynamicBinding.getRoot();
    }

    private View getBusinessOpportunities() {
        mFooterBinding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.item_footer_self_business_opportunity, binding.firstordernestingRecyclerview, false);
        mFooterBinding.businessOpportunityRecycleView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
        mFooterBinding.businessTypeRecycleView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false));
        mFooterBinding.businessOpportunityRecycleView.setHasFixedSize(true);
        if (mBusinessAdapter == null) {
            mBusinessAdapter = new SelfBusinessOpportunityAdapter(R.layout.item_self_business_opportunity);
            mBusinessAdapter.bindToRecyclerView(mFooterBinding.businessOpportunityRecycleView);
        }
        if (mBusinessTypeAdapter == null) {
            mBusinessTypeAdapter = new BusinessTypeAdapter(R.layout.item_website_tab_first);
            mBusinessTypeAdapter.bindToRecyclerView(mFooterBinding.businessTypeRecycleView);
        }
        mFooterBinding.tvBusinessMore.setOnClickListener(v -> {
            if (mBusinessType.equals("2")) {//订阅商机
                SubscribeBusinessActivity.Companion.launch(getContext());
            } else {
                BusinessOpportunityHallActivity.start(getContext(), 0, "");
            }
        });
        mBusinessAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mBusinessAdapter.getItem(position) != null) {
                    AdapterJumpPush.getInstance(getActivity(), mBusinessAdapter.getItem(position), null);
                }
            }
        });
        View empty = LayoutInflater.from(getContext()).inflate(R.layout.layout_empty_view, mFooterBinding.businessOpportunityRecycleView, false);
        ((TextView) empty.findViewById(R.id.no_data_tv)).setText("暂无商机");
        mBusinessAdapter.setEmptyView(empty);
        mFooterBinding.businessOpportunityRecycleView.addItemDecoration(
                new RecyclerCustomDecoration(
                        0f,
                        0f,
                        0f,
                        getResources().getDimension(R.dimen.dp1), getResources().getColor(R.color.color_main_bg)
                )
        );
        mBusinessTypeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<PickFilterEntity> data = mBusinessTypeAdapter.getData();
                if (position > -1 && position < data.size() - 1) {
                    if (data.get(position).isChoose()) {
                        return;
                    }
                }
                if (!data.isEmpty()) {
                    for (int i = 0; i < data.size(); i++) {
                        if (i == position) {
                            mBusinessType = data.get(i).getNo();
                            data.get(i).setChoose(true);
                        } else {
                            data.get(i).setChoose(false);
                        }
                    }
                }
                if (mBusinessType.equals("0")) { //商机大厅
                    viewModel.getBusinessListData();
                } else if (mBusinessType.equals("2")) { //自主订阅
                    viewModel.getSubscribeBusinessListData();
                }
                viewModel.businessList.postValue(new ArrayList<>());
                mBusinessTypeAdapter.notifyDataSetChanged();
            }
        });
        mFooterBinding.getRoot().setVisibility(View.GONE);
        return mFooterBinding.getRoot();
    }

    private void initHeadCompanyRecycle() {
        if (mHeadCompanyRecyclerView == null) {
            mHeadCompanyRecyclerView = new RecyclerView(getContext());
        }
        mHeadCompanyRecyclerView.setNestedScrollingEnabled(false);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mHeadCompanyRecyclerView.setLayoutParams(lp);
        mHeadCompanyRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 5));
        mHeadCompanyAdapter = new SelfSecondOrderNestingAdapter(getContext(), null);
        mHeadCompanyRecyclerView.setAdapter(mHeadCompanyAdapter);
        mHeadCompanyAdapter.setOnItemClick(new AdapterOnItemClick<PermissionMenuEntity.ListEntity>() {
            @Override
            public void onItemClick(PermissionMenuEntity.ListEntity listEntity, int position) {
                adapterItemClick(listEntity, position);
            }
        });

        if (mNoAuthRecyclerView == null) {
            mNoAuthRecyclerView = new RecyclerView(getContext());
        }
        mNoAuthRecyclerView.setNestedScrollingEnabled(false);
        mNoAuthRecyclerView.setLayoutParams(lp);
        mNoAuthRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 5));
        mNoAuthHeadAdapter = new SelfSecondOrderNestingAdapter(getContext(), null);
        mNoAuthRecyclerView.setAdapter(mNoAuthHeadAdapter);
        mNoAuthHeadAdapter.setOnItemClick(new AdapterOnItemClick<PermissionMenuEntity.ListEntity>() {
            @Override
            public void onItemClick(PermissionMenuEntity.ListEntity listEntity, int position) {
                adapterItemClickNoAuth(listEntity, position);
            }
        });

    }

    private void adapterItemClickNoAuth(PermissionMenuEntity.ListEntity entity, int position) {
        if (!TextUtils.isEmpty(entity.getName())) {
            if (!isEnableClick) return;
            switch (entity.getName()) {
                case "0_gerenrenzheng":
                    switch (userEntity.getPersonalAuthAuditStatus()){
                        case 0:
                            CertificationActivity.start(getContext(), "1");
                            break;
                        case 1:
                        case 2:
                        case 3:
                            ActivityJump.jumpToActivity(getActivity(), UserAuthDetailActivity.class, Pair.create("userNo", this.userEntity.getNo()));
                            break;
                    }
                    break;
                case "0_sijirenzheng":
                    if (userEntity == null) return;
//                    if (mPersonAuth) {
                    // 2021-12-04 (紧急需求) 如果未个人认证，也是可以进行司机认证的。
                    //司机认证字段 @"NONE"-未认证 @"STANDBY"-认证中  @"FAIL"-认证失败 @"SUCCESS"-认证成功
                    int status = -1;
                    if (UserOperating.getInstance().getUserInfo() != null && UserOperating.getInstance().getUserInfo().getDriverAuth() != null) {
                        status = UserOperating.getInstance().getUserInfo().getDriverAuth().getStatus();
                    }
                    if (status != -1) {
                        DriverInfoActivity.start(getActivity());
                    } else {
                        Intent intent = new Intent(getActivity(), AddDriverInfoActivity.class);
                        intent.putExtra("name", userEntity.getRealName());
                        intent.putExtra("cardId", userEntity.getIdentityCard());
                        startActivity(intent);
                    }
                    break;
                case "0_tuanduirenzheng":
                    if (userEntity.getPersonalAuth() != 1) {
                        userEntity.setRealName("");
                        userEntity.setIdentityCard("");
                        userEntity.setTelPhone(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LOGIN_PHONE, ""));
                    }
                    TeamAuthActivity.start(getContext(), userEntity.getRealName(), userEntity.getIdentityCard(), userEntity.getTelPhone());
                    break;
                case "0_zuzhirenzheng":
                    OrganizationAuthActivity.launch(getContext());
                    break;
                case "0_qiyerenzheng":
                    RegisterActivity3.start(getContext(), true);
                    break;
                case "0_jiaruqiye":
                    JoinCompanyActivity.start(getContext());
                    break;
            }
        }
    }

    //头部item 点击事件
    private void adapterItemClick(PermissionMenuEntity.ListEntity entity, int position) {
        if (!isEnableClick) {
            return;
        }
        if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
            ACAdminDialogUtils.showACDialog(ACAdminDialogUtils.TYPE_AUTH_NO_AC, getContext());
            return;
        }
        if (!TextUtils.isEmpty(entity.getName())) {
            switch (entity.getName()) {
                case "7_dingdan":
                    if (mType == 1 || mType == 0) {
                        if (mMenus.isEmpty()) {
                            mMenus.addAll(mTempMenus);
                        }
                        AgentTotalOrderActivity.Companion.launch(getContext(), mMenus);
                    }
                    break;
                case "10_xunjia":
                    if (mType == 2 || mType == 1) {
                        AgentEnquiryActivity.Companion.launch(getContext(), mType, permissionEnquiryShop);
                    } else if (mType == 0) {
                        if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                            ACAdminDialogUtils.showACDialog(ACAdminDialogUtils.TYPE_AUTH_NO_AC, getContext());
                            return;
                        }
                        AgentEnquiryActivity.Companion.launch(getContext(), mType, permissionEnquiryShop);
                    }
                    break;
                case "8_fukuan":
                    if (mType == 1) {
                        if (goToPayEnable) {
                            BusinessManagementActivity.start(getContext(), 1);
                        } else {
                            MToast.showToast(getContext(), "暂无权限，请联系管理员分配");
                        }
                        break;
                    }
                case "11_ucshenqing":
                    if (mType == 1) {
                        AgentApplyActivity.Companion.launch(getContext(), mApplyMenus);
                        break;
                    }
                case "20_yuangongshenhe"://员工审核
                case "24_xinyuangong":
                    if (mType == 1) {
                        if (mStaffCheckMenus.isEmpty()) {
                            MToast.showToast(getContext(), "暂无权限，请联系管理员分配");
                        } else {
                            AgentApplyActivity.Companion.launch(getContext(), mStaffCheckMenus, "员工审核");
                        }
                    }
                    break;
                case "21_huiyuanshenhe"://会员审核
                case "24_xinhuiyuan":
                    if (mType == 1 || mType == 0) {
                        if (mCustomerCheckMenus.isEmpty()) {
                            MToast.showToast(getContext(), "暂无权限，请联系管理员分配");
                        } else {
                            AgentApplyActivity.Companion.launch(getContext(), mCustomerCheckMenus, "会员审核");
                        }
                    }
                    break;
                case "24_xinchengyuan":
                    if (mType == 1) {
                        SpecialMemberActivity.Companion.launch(getContext(), false);
                    }
                    break;
                case "13_ucjicai":
                    if (mType == 1) {
                        if (mAgentCentralizedMiningMenus.isEmpty()) {
                            mAgentCentralizedMiningMenus.addAll(mTempAgentCentralizedMiningMenus);
                        }
                        mReallyAgentCentralizedMiningMenus.clear();
                        mReallyAgentCentralizedMiningMenus.addAll(mAgentCentralizedMiningMenus);
                        if (mReallyAgentCentralizedMiningMenus.isEmpty()) {
                            MToast.showToast(getContext(), "暂无权限，请联系管理员分配");

                        } else {
                            AgentCentralizedMiningActivity.Companion.launch(getContext(), mReallyAgentCentralizedMiningMenus);
                        }
                    }
                    break;
                case "5_hanxun":
                    WebSiteInquiryActivity.Companion.start(getContext(), mInquiryNum);
                    break;
                case "16_hetong":
                    if (mType == 1) {
                        viewModel.getCompanyDetail(getContext(), 3, mIsUser);
                    }
                    break;
                case "24_baoming":
                    RegistrationActivity.Companion.launch(getContext());
                    break;
                case "24_baojia":
                    QuotationActivity.Companion.launch(getContext());
                    break;
                default:
                    MenuClickUtils.getInstance().handlerClickItem(getContext(), entity, mType);
            }
        }
    }

    /**
     * 初始化 左边抽屉弹框布局
     *
     * @author 张驰 @date 2021/4/23 11:12
     */
    private void initPopWindow() {
        if (selfPopWindow == null) {
            selfPopWindow = SelfPopWindow.newInstance();
            //通过接口回调设置点击监听
            selfPopWindow.setClickSelfItemListener(new SelfPopWindow.ClickSelfItemListener() {
                @Override
                public void click(String nameStr) {
                    //判断点击
                    switch (nameStr) {
                        case "我的信息":
                            //跳转到个人信息界面
                            PersonInfoActivity.startActivity(getActivity(), companyList);
                            break;
                        case "二维码名片":
                            //跳转到二维码界面
                            SelfQrCodeActivity.start(getContext());
                            break;
                        case "员工加入":
                            //跳转到加入企业界面
                            JoinCompanyActivity.start(getContext());
                            break;
                        case "官方客服":
                            //打开客服弹窗
                            showDialog();
                            //OrganizationDetailActivity.Companion.launch(getContext(), new OrganizationAuthEntity());
                            break;
                        case "分享App":
                            //暂未开放
                            Toast.makeText(activity, "正在升级中", Toast.LENGTH_SHORT).show();
                            break;
                        case "设置":
                            //暂未开放
                            SettingActivity.start(getContext());
//                        TeamFunctionActivity.start(getContext());
                            break;
                    }
                }
            });
        }
    }

    /**
     * 给控件设置点击事件
     *
     * @author 张驰 @date 2021/4/23 11:10
     */
    private void initClickView() {
        //登录按钮
        binding.loginView.setOnClickListener(this);
        //公司列表
        binding.companyLayout.setOnClickListener(this);
        binding.companyLayout1.setOnClickListener(this);
        //设置
        binding.btSelfSettings.setOnClickListener(this);
        //系统提醒
        binding.btSelfReminder.setOnClickListener(this);
        //头像
        binding.companyLogoIv.setOnClickListener(this);
        //未登录背景图
        binding.longimgs.setOnClickListener(this);
        //扫一扫
        binding.btScan.setOnClickListener(this);
        //企业网站入口
        binding.tvSiteEntrance.setOnClickListener(this);
        binding.paixu.setOnClickListener(this);
        binding.paixu1.setOnClickListener(this);
        binding.paixu2.setOnClickListener(this);
    }

    /**
     * 主UI样式初始化
     */
    private void initWindow() {
        //测量隐藏背景高度
        binding.appBar.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {
                    //展开状态
                    if (flag != true) {
                        flag = true;
                    }
                    isExpanded = true;
                } else if (state == State.COLLAPSED) {
                    //折叠状态
                    flag = false;
                    binding.companyLayout.setVisibility(View.VISIBLE);
                    isExpanded = false;

                } else {
                }
            }

            @Override
            public void onAlphaChanged(float alpha) {
                if (alpha == 0) {
                    binding.companyLayout.setEnabled(false);
                }
                if (alpha == 1) {
                    binding.companyLayout.setEnabled(true);
                }
                binding.companyLayout.setAlpha(alpha);
            }
        });
    }

    //滑动到指定位置
    private void tipPosition(int position) {
        //mTabPosition = tab.getPosition();
        if (!isRecyclerViewScroll) {
            LinearLayoutManager mLayoutManager = (LinearLayoutManager) binding.firstordernestingRecyclerview.getLayoutManager();
            if (mLayoutManager != null) {
                mLayoutManager.scrollToPositionWithOffset(position, 0);
            }
        }
        //smoothMoveToPosition(binding.firstordernestingRecyclerview, tab.getPosition());
    }


    /**
     * event监听登录和登出的状态
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_USER_CENTER_JUMP ||
                event.getMessageTag() == EventConstant.EVENT_WEB_VIEW_JUMP) {
            isLoginJump = true;
            getData();
            if (event.getMessageTag() == EventConstant.EVENT_WEB_VIEW_JUMP) {
                mIsH5Login = true;
            }
            EventBus.getDefault().removeStickyEvent(event);
        } else if (event.getMessageTag() == EventConstant.EVENT_LOGIN_OUT) {
            //退出操作图片默认
            Glide.with(this)
                    //加载设置宽高限制
                    .load(getResources().getDrawable(R.mipmap.def_photo))
                    //显示圆图
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    //设置为头像
                    .into(binding.companyLogoIv);
            SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LOGIN_TOKEN, "");
            firstOrderNestingAdapter.setNewData(new ArrayList<>());
            getData();
        } else if (event.getMessageTag() != EventConstant.EVENT_LOGIN) {
            isLoginJump = true;
            getData();
        }
    }

    /**
     * logo上传刷新当前身份的头像
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LogoRefreshEvent event) {
        viewModel.getCompanyList();
        EventBus.getDefault().removeStickyEvent(event);
    }

    /**
     * event监听刷新状态
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_USER_CENTER_JUMP) {
            getData();
            isLoginJump = true;
            EventBus.getDefault().removeStickyEvent(event);
        }
    }

    /**
     * 当token变更的时候更新个人中心界面
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LoginTokenEvent event) {
        if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            if (binding != null) {
                binding.smartRefreshLayout.setEnableLoadMore(false);
                binding.smartRefreshLayout.setEnableRefresh(false);
                isLoginJump = true;
                //退出登录后清空用户状态信息
                IMUtils.getInstance().clearLoginUserInfo();
                showNoLogin();
            }
        }
        EventBus.getDefault().removeStickyEvent(event);
    }

    /**
     * event监听主企业切换的状态
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MainEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_MAIN_ENTERPRISE_SWITCHING) {
            getData();
        }
    }

    /**
     * event监听用户上传头像的状态
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(UploadAvatarEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_UPLOAD_AVATAR) {
            getData();
        }
    }

    /**
     * 询价或者集采点击详情之后删除 刷新未读数量
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onRefresh(RefreshUnReadNumEvent event) {
        viewModel.getTotalUnReadMsg(true);
        EventBus.getDefault().removeStickyEvent(event);
    }

    /**
     * 懒加载
     */

    @Override
    protected void onLazyLoad() {
        //判断当前SharedPreferenceUtil中是否已登录有账号
        getData();
    }

    /**
     * event监听用户的认证的状态
     */

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(AuthenticationEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_USER_AUTHENTICATION) {
            if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "")) &&
                    !TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                //如果是已登录状态 手机缓存中没有保存任何公司信息
                isLoginJump = true;
            }
            getData();
        } else if (event.getMessageTag() == EventConstant.EVENT_JOIN_COM) {
            //event用户加入企业后刷新

            viewModel.getCompanyList();

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(WebEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_APPROVAL_REFRESH) {
            viewModel.getApplyCount();
        }
    }


    /**
     * 判断当前SharedPreferenceUtil中是否已登录有账号
     */
    public void getData() {
        MLog.d("首页都等", "getData");
        //判断当前SharedPreferenceUtil中是否已登录有账号
        if (!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            binding.smartRefreshLayout.setEnableLoadMore(false);
            binding.smartRefreshLayout.setEnableRefresh(true);

            if (isFirstRefresh && binding.smartRefreshLayout != null && !binding.smartRefreshLayout.isRefreshing()) {
                binding.smartRefreshLayout.autoRefresh();//显示刷新动画并且触发刷新事件
            }

            DialogHelper.dismissProgressDialog();
            showLogin();
        } else {
            binding.smartRefreshLayout.setEnableLoadMore(false);
            binding.smartRefreshLayout.setEnableRefresh(false);
            showNoLogin();
            activity.upDataMyTabIcom("未登录", "");
        }

    }

    /**
     * 显示页面数据
     */
    public void showLogin() {
        //显示假图片
        if (!isFirst) {
            isFirst = true;
            binding.longimg.setVisibility(View.VISIBLE);
            binding.longimgs.setVisibility(View.VISIBLE);
        }
        //设置头部缓存
        if (!isLoginJump) {
            setDefaultCacheName();
        } else {
            if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, true)) {
                String phone = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "");
                binding.companyName.setText(phone);//注册进来为认证 显示手机号
                binding.companyName1.setText(phone);
                binding.companyLayout.setVisibility(View.VISIBLE);
                binding.companyLayout1.setVisibility(View.VISIBLE);
            }
        }
        // 获取用户开户信息
        if (mBank == null) {
            mBank = new H5MsgEntity();
        }
        binding.rlContent.setVisibility(View.VISIBLE);
        mBank.msgType = "cmd_companyAuthState";
        //获取用户信息
        viewModel.getUserInfo();
        //获取企业列表
        viewModel.getCompanyList();
        //显示用户信息布局
        binding.userInfoLayout.setVisibility(View.VISIBLE);
        mType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1);
        if (SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, true)) {
            //显示用户名
            if (mType != 0) {
                binding.tvUserName.setVisibility(View.VISIBLE);
            } else {
                binding.tvUserName.setVisibility(View.GONE);
            }
            binding.tvUserPhone.setVisibility(View.VISIBLE);
            binding.companyDown.setVisibility(View.VISIBLE);
            binding.companyDown1.setVisibility(View.VISIBLE);
        } else {
            binding.tvUserName.setVisibility(View.GONE);
            binding.tvUserPhone.setVisibility(View.GONE);
            binding.companyDown.setVisibility(View.GONE);
            binding.companyDown1.setVisibility(View.GONE);
        }
        //显示用户的第一级recycleview
        binding.firstordernestingRecyclerview.setVisibility(View.VISIBLE);
        //用户登录成功后，隐藏长图
        //显示未登录的布局
        isEnableClick = false;
        binding.noLoginLl.setVisibility(View.GONE);
//        setLlHeadPersonOrCompany(mType);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == MANGER && resultCode == RESULT_OK) {
            refreshPermissionMenu();
        } else if (data != null && requestCode == SECONDMORE && resultCode == RESULT_OK) {
            int companyType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, true) ? 1 : 0);
            String no;
            if (mangertype != 0) {
                no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
            } else {
                no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
            }
            viewModel.GetToplist(1, no, mangertype);
            Log.e("xx", "李豆");
        }
    }

    /**
     * 刷新权限一级菜单数据
     */
    private void refreshPermissionMenu() {
        CompanyEntity entity = new CompanyEntity();
        entity.setCompNo(companyNo);
        entity.setType(mangertype);
        if (mPersonAuth) {
            viewModel.getPermissionMenu(companyNo, mangertype);
            viewModel.getPermissionHuiYuan();
        } else {
            viewModel.getNoAuthPermissionMenu(companyNo);
        }

    }

    public void showchagnyongMenu(SecondMore.DataDTO dataDTO) {
        if (dataDTO == null || dataDTO.getIconList() == null) {
            return;
        }
        if (dataDTO.getIconList().size() > 0) {
            dataList.get(0).getList().get(0).setList(dataDTO.getIconList());
            int position = 0;
            if (position < dataList.size()) {
                reallyDataList.clear();
                if (dataList.get(position) != null && dataList.get(position).getList() != null && !dataList.get(position).getList().isEmpty()) {
                    reallyDataList.addAll(dataList.get(position).getList());
                }
                tipPosition(0);
                firstOrderNestingAdapter.setDatas(reallyDataList);
                setCanNsEnable(position);
            }
        }
    }

    private void isShowHeader(boolean isHome) {
        if (isHome) {
            if (mHeaderBinding != null) {
                mHeaderBinding.getRoot().setVisibility(View.VISIBLE);
            }
        } else {
            if (mHeaderBinding != null) {
                mHeaderBinding.getRoot().setVisibility(View.GONE);
            }
        }
    }

    //是否展示底部 只有企业有
    private void isShowFooter(int type, boolean isHome) {
        if ((type == 1||type==0) && isHome) {
            if (mFooterBinding != null) {
                mFooterBinding.getRoot().setVisibility(View.VISIBLE);
            }
            if (mDynamicBinding != null&&type!=0) {
                mDynamicBinding.getRoot().setVisibility(View.VISIBLE);
            }else {
                mDynamicBinding.getRoot().setVisibility(View.GONE);
            }
        } else {
            if (mFooterBinding != null) {
                mFooterBinding.getRoot().setVisibility(View.GONE);
            }
            if (mDynamicBinding != null) {
                mDynamicBinding.getRoot().setVisibility(View.GONE);
            }
        }
        if (isHome) {
            ViewGroup.LayoutParams lp = binding.firstordernestingRecyclerview.getLayoutParams();
            if (SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                if (type == 1 || type == 0) {
                    lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
                } else {
                    lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                }
            } else {
                if (type == 0) {
                    lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
                } else {
                    lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                }
            }
            binding.firstordernestingRecyclerview.setLayoutParams(lp);
        }
    }

    private void setDefaultCacheName() {
        //显示缓存的公司名称
        String companyName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        binding.companyName.setText(companyName);
        binding.companyName1.setText(companyName);
        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, -1);
        String realName = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME, "");
        if (!TextUtils.isEmpty(realName)) {
            if (type == 0) {
                binding.tvUserName.setVisibility(View.GONE);
                binding.companyName.setText(realName);
                binding.companyName1.setText(realName);
            } else {
                binding.tvUserName.setVisibility(View.VISIBLE);
            }
            binding.tvUserName.setText(realName);
        }
        if (!TextUtils.isEmpty(binding.companyName1.getText().toString())) {
            //初始化进来显示名字
            binding.companyLayout1.setVisibility(View.VISIBLE);
            //获取缓存基本信息中的手机号码
            String telephone = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LOGIN_PHONE, "");
            //判断是否为空
            if (!TextUtils.isEmpty(telephone)) {
                binding.tvUserPhone.setText(telephone);
            }
        }
    }

    /**
     * 显示没有没有账号或者没有登录时的界面
     */
    public void showNoLogin() {
        binding.rlContent.setVisibility(View.GONE);
        //显示未登录的布局
        binding.noLoginLl.setVisibility(View.VISIBLE);
        //隐藏用户的第一级recycleview
        binding.firstordernestingRecyclerview.setVisibility(View.GONE);
        //用户未登录时，显示长图
        binding.longimg.setVisibility(View.VISIBLE);
        binding.longimgs.setVisibility(View.VISIBLE);
        //隐藏用户信息布局
        binding.userInfoLayout.setVisibility(View.GONE);
        //隐藏公司列表的布局
        binding.companyLayout.setVisibility(View.GONE);
        binding.companyLayout1.setVisibility(View.GONE);
        //隐藏企业网站入口
        binding.tvSiteEntrance.setVisibility(View.GONE);
        //隐藏认证TAB
//        binding.xbanner.setVisibility(View.GONE);
        //不同控件的父布局
        binding.llHeadPersonCompany.setVisibility(View.GONE);
        //binding.tablayout.setVisibility(View.GONE); //退出登录 tab隐藏
        //变更【我的】按钮模块未未登陆状态
        activity.upDataMyTabIcom("未登录", "");
        //退出登录 清除之前的信息
        binding.companyLayout.setVisibility(View.GONE);
        binding.companyLayout.setVisibility(View.GONE);
        binding.tvUserName.setText("");
        binding.tvUserPhone.setText("");
        binding.companyName.setText("");
        binding.companyName1.setText("");
        isShowFooter(0, true);
        isShowHeader(false);
        isFirstRefresh = true;
        FrameLayout.LayoutParams lpHeadRoot = (FrameLayout.LayoutParams) binding.llHeadRoot.getLayoutParams();
        FrameLayout.LayoutParams lpHeadMsg = (FrameLayout.LayoutParams) binding.llHeadMsg.getLayoutParams();
        binding.llHeadMsg.setPadding(0, 0, 0, 0);
        lpHeadMsg.bottomMargin = 0;
        lpHeadRoot.bottomMargin = 0;
        binding.llHeadMsg.setLayoutParams(lpHeadMsg);
        binding.llHeadRoot.setLayoutParams(lpHeadRoot);
    }

    /**
     * 初始化 切换企业弹框布局
     *
     * @author 张驰 @date 2021/4/23 11:18
     */
    private void initCompanyChangePop() {
        if (companyChangePop == null) {
            companyChangePop = new CompanyChangeDialog(getActivity(), null, binding.rlPop);
            companyChangePop.setDialogClickCallBack(new CompanyChangeDialog.DialogClickCallBack() {

                @Override
                public void onItemClick(CompanyEntity provinceEntity, int position) {
                    mangertype = provinceEntity.getType();
                    if (!TextUtils.isEmpty(provinceEntity.getCompNo()) && provinceEntity.getCompNo().equals(comNo)) {
                        companyChangePop.dismiss();
                        return;//如果这次点击的根上一次的no一样 不响应事件
                    }
                    //设置切换后企业操作(同步后台身份)
                    viewModel.toggleCurrentCompany(provinceEntity);
                    isEnableClick = false;
                    binding.llIndicator.setVisibility(View.GONE);//切换企业先隐藏指示器
                    binding.paixu.setVisibility(View.GONE);
                    binding.paixu1.setVisibility(View.GONE);
                    binding.paixu2.setVisibility(View.GONE);
//                    EventBus.getDefault().postSticky(EventConstant.EVENT_REFRESH_MAIN);
                    companyChangePop.setItem(position);
                    companyChangePop.dismiss();
                }
            });
            companyChangePop.setOnDismissListener(dialog -> {
                binding.companyDown.setImageResource(R.mipmap.btn_expand_down);
                if (flag) {
                    binding.companyLayout.setAlpha(0);
                }
            });

        }
    }

    /**
     * 更新切换企业后数据刷新
     */
    private void setMyComSetting(CompanyEntity provinceEntity) {
        //获取用户的基本信息
        //viewModel.getEssentialInformation(provinceEntity);
        //获取我的页面菜单数据
        //viewModel.getPermissionMenu(provinceEntity);
        //设置展示主企业的基本信息
        //setCurrentCompany(provinceEntity);
        //如果是h5 token失效登录的话 刷新企业网站的信息
//        if (provinceEntity.getType() == 1) {
//            //获取企业联动商户信息
//            viewModel.getBusinessInfoByCompany();
//        } else {
//            //获取个人和团队信息
//            viewModel.getBusinessInfoByUser();
//        }
    }

    /**
     * 显示 切换企业弹框布局
     *
     * @author 张驰 @date 2021/4/23 11:18
     */
    private void showCompanyChangePop() {
        if (flag) {
            binding.companyLayout.setAlpha(1);
        }
        if (companyChangePop == null) {
            initCompanyChangePop();
        }
        //公司弹窗设置参数集合
        companyChangePop.setData(companyList);
        //根据comNo设置默认选中的item
        String no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        if (!companyList.isEmpty()) {
            if (!TextUtils.isEmpty(no)) {
                for (int i = 0; i < companyList.size(); i++) {
                    if (no.equals(companyList.get(i).getCompNo())) {
                        companyChangePop.setItem(i);
                        break;
                    }
                }
            }
        }
        //设置向上的图片
        binding.companyDown.setImageResource(R.mipmap.btn_expand_up);
        //展示显示弹窗
        companyChangePop.show();
    }

    /**
     * 设置点击事件
     */
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.paixu:
            case R.id.paixu2:
//                Intent intent =new Intent(getActivity(),MangermoreActivity.class);
//                intent.putExtra("list", (Serializable) dataList);
//                startActivityForResult(intent,MANGER);
//                break;
            case R.id.paixu1:
                Intent intent1 = new Intent(getActivity(), MangermoreActivity.class);
                intent1.putExtra("list", (Serializable) dataList);
                startActivityForResult(intent1, MANGER);
                break;
            //点击登录按钮的事件
            case R.id.login_view:
                VerificationCodeLoginActivity.start(activity, EventConstant.EVENT_USER_CENTER_JUMP);
                break;
            case R.id.attestation_now_tv:
                AuthActivity3.start(getContext());
                break;
            case R.id.tv_version:
                break;
            case R.id.company_layout:
            case R.id.company_layout1:
                //判断是否存在（以前的公共接口，无公司也返回一个空公司，暂时用公司名判断是否存在）
                if (null != companyList && !companyList.isEmpty() && mPersonAuth) {
                    showCompanyChangePop();
                }
                break;
            case R.id.bt_self_settings:
                //点击用户头像时，判断是否已经登录，如果未登录则提示登录账户
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    Toast.makeText(activity, "请先登录", Toast.LENGTH_SHORT).show();
                    return;
                }
                //跳转个人设置界面
                SettingActivity.start(getActivity());
                break;
            case R.id.bt_self_reminder:
                //未登录状态下提示登录
                MToast.showToast(activity, "功能暂未开放");

//                if (TextUtils.isEmpty(NimUIKit.getAccount())) {
//                    MToast.showToast(activity, "请先登录");
//                } else {
//                    //登录状态下跳转系统消息界面
//                    NimUIKit.startP2PSession(getActivity(), "systemnoti");
//                }
                break;
            case R.id.company_logo_iv:
                //点击用户头像时，判断是否已经登录，如果未登录则提示登录账户
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    Toast.makeText(activity, "请先登录", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (selfPopWindow.isAdded()) {
                    selfPopWindow.dismiss();
                } else {
                    selfPopWindow.show(getActivity().getSupportFragmentManager(), "show");
                }
                break;
            //未登录，点击长图的事件
            case R.id.longimgs:
                //跳转到登录界面
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(activity, EventConstant.EVENT_USER_CENTER_JUMP);
                }
                break;
            case R.id.bt_scan:
                //扫一扫
                checkPermission();
                break;
            case R.id.go_identification:
                AuthActivity3.start(getActivity());
                break;
            case R.id.tv_site_entrance: //企业网店入口
                if (!ClickUtils.isDoubleClick()) {
                    String companyNo = null;
                    if (mType == 0) {
                        companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
                    } else {
                        companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
                    }
                    if (TextUtils.isEmpty(companyNo)) {
                        MToast.showLongToast(getContext(), "请切换个人身份或企业身份");
                        return;
                    }
                    WebsiteInfoActivity.start(getActivity(), companyNo, mType, true);
                }
                break;
        }
    }

    private void setLlHeadPersonOrCompany(int type) {
        if (mHeaderBinding == null) {
            return;
        }
        mHeaderBinding.llHeadPersonCompany.removeAllViews();
        binding.llHeadPersonCompany.removeAllViews();
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) binding.llHeadPersonCompany.getLayoutParams();
        FrameLayout.LayoutParams lpHeadRoot = (FrameLayout.LayoutParams) binding.llHeadRoot.getLayoutParams();
        FrameLayout.LayoutParams lpHeadMsg = (FrameLayout.LayoutParams) binding.llHeadMsg.getLayoutParams();
        mHeaderBinding.llHeadPersonCompany.setVisibility(View.VISIBLE);
        binding.llHeadRoot.setVisibility(View.GONE);
        binding.llHeadPersonCompany.setVisibility(View.GONE);
        if (type == 0) {
//            if (SharedPreferenceUtil.getInstance().getBoolean(SharedPreferenceUtil.PERSON_AUTH, false)){
//                View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_self_person_header, null, false);
//                TextView tvJoin = view.findViewById(R.id.tvJoin);
//                tvJoin.setOnClickListener(v -> {
//                    if (!isEnableClick) return;
//                    if (!mPersonAuth) {
//                        optState();
//                        return;
//                    }
//                    JoinCompanyActivity.start(getContext());
//                });
//                TextView tvCreate = view.findViewById(R.id.tvCreate);
//                tvCreate.setOnClickListener(v -> {
//                    if (!isEnableClick) return;
//                    if (!mPersonAuth) {
//                        optState();
//                        return;
//                    }
//                    AuthActivity3.start(getContext());
//                });
//                lp.height = SizeUtils.dp2px(45);
//                lp.bottomMargin = SizeUtils.dp2px(0);
//                lp.leftMargin = SizeUtils.dp2px(15);
//                lp.rightMargin = SizeUtils.dp2px(15);
//                binding.llHeadPersonCompany.addView(view);
//                binding.llHeadPersonCompany.setBackgroundResource(R.drawable.img_self_person_header_bg);
//                //binding.llHeadPersonSecond.setVisibility(View.GONE);
//                binding.llHeadMsg.setPadding(0,0,0, SizeUtils.dp2px(45));
//                lpHeadMsg.bottomMargin = 0;
//                lpHeadRoot.bottomMargin = 0;
//            } else {
//                if (SharedPreferenceUtil.getInstance().getBoolean(SharedPreferenceUtil.PERSON_AUTH, false)){
//                    lp.height = SizeUtils.dp2px(81);
//                    binding.llHeadMsg.setPadding(0,0,0, SizeUtils.dp2px(66));
//                    lpHeadMsg.bottomMargin = SizeUtils.dp2px(25);
//                    lpHeadRoot.bottomMargin = SizeUtils.dp2px(5);
//                    binding.llHeadPersonCompany.setPadding(0, SizeUtils.dp2px(0), 0, SizeUtils.dp2px(0));
//                } else {
            binding.llHeadPersonCompany.addView(getNoAuthTipView());
            lp.height = SizeUtils.dp2px(105);
            binding.llHeadMsg.setPadding(0, 0, 0, SizeUtils.dp2px(78));
            lpHeadMsg.bottomMargin = SizeUtils.dp2px(37);
            lpHeadRoot.bottomMargin = SizeUtils.dp2px(5);
            binding.llHeadPersonCompany.setPadding(0, SizeUtils.dp2px(12), 0, SizeUtils.dp2px(12));//未认证
            //}
            lp.bottomMargin = SizeUtils.dp2px(0);
            lp.leftMargin = SizeUtils.dp2px(10);
            lp.rightMargin = SizeUtils.dp2px(10);
            binding.llHeadPersonCompany.addView(mNoAuthRecyclerView);
            binding.llHeadPersonCompany.setBackground(getResources().getDrawable(R.drawable.shape_rd10_white_bg));
            //binding.llHeadPersonCompany.setVisibility(View.GONE);

            //}
            viewModel.getNoAuth(SharedPreferenceUtil.getInstance().getBoolean(SharedPreferenceUtil.PERSON_AUTH, false));
            binding.llHeadPersonCompany.setLayoutParams(lp);
            binding.llHeadRoot.setVisibility(View.VISIBLE);
            binding.llHeadPersonCompany.setVisibility(View.VISIBLE);
            binding.llHeadMsg.setBackgroundResource(R.drawable.bg_self_user_info_grait);
        } else {
            lpHeadMsg.bottomMargin = 0;
            lpHeadRoot.bottomMargin = 0;
            binding.llHeadMsg.setPadding(0, 0, 0, 0);
            binding.llHeadMsg.setBackgroundResource(R.drawable.bg_self_user_info_person_bg);
        }
        mHeaderBinding.llHeadPersonCompany.addView(mHeadCompanyRecyclerView);
        lp = (LinearLayout.LayoutParams) mHeaderBinding.llHeadPersonCompany.getLayoutParams();
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        lp.leftMargin = SizeUtils.dp2px(10);
        lp.rightMargin = SizeUtils.dp2px(10);
        lp.bottomMargin = SizeUtils.dp2px(5);
        mHeaderBinding.llHeadPersonCompany.setBackground(getResources().getDrawable(R.drawable.shape_rd10_white_bg));
        //binding.llHeadPersonCompany.setVisibility(View.GONE);
        mHeaderBinding.llHeadPersonCompany.setPadding(0, SizeUtils.dp2px(15), 0, SizeUtils.dp2px(15));
        mHeaderBinding.llHeadPersonCompany.setLayoutParams(lp);
        mHeaderBinding.llHeadPersonCompany.setVisibility(View.VISIBLE);
        binding.llHeadMsg.setLayoutParams(lpHeadMsg);
        binding.llHeadRoot.setLayoutParams(lpHeadRoot);
        tipPosition(0);
        viewModel.getApprovalAgent(type);
    }

    private ImageSpan mImageSpan;

    //未认证 提示
    @SuppressLint("UseCompatLoadingForDrawables")
    private View getNoAuthTipView() {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        TextView tv = new TextView(getContext());
        //tv.setText("(需 需认证后才能展示或操作业务)");
        tv.setTextColor(getResources().getColor(R.color.color_tab_three));
        tv.setTextSize(12);
        tv.setGravity(Gravity.CENTER);
        lp.leftMargin = SizeUtils.dp2px(15f);
        tv.setPadding(0, 0, 0, 0);
        tv.setLayoutParams(lp);
        mImageSpan = new CenterImageSpan(getContext(), R.drawable.icon_no_auth_tip);
        SpannableString ssb = new SpannableString("需 (需认证后才能展示或操作业务)");
        ssb.setSpan(mImageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(ssb);
        return tv;
    }

    public void renderHeadView(List<PermissionMenuEntity.ListEntity> mList) {
        listHeadCompany.clear();
        listHeadCompany.addAll(mList);
        mHeadCompanyAdapter.clearDatas();
        mHeadCompanyAdapter.getDatas().addAll(listHeadCompany);
        mHeadCompanyAdapter.notifyDataSetChanged();
//        if (mType == 0) {
//            binding.llHeadPersonSecond.setVisibility(View.VISIBLE);
//        } else {
//            binding.llHeadPersonCompany.setVisibility(View.VISIBLE);
//        }
        binding.appBar.setExpanded(true);
    }

    public void renderNoAuthView(List<PermissionMenuEntity.ListEntity> mList) {
        if (userEntity.getPersonalAuthAuditStatus()==2){
            mList.remove(0);
        }
        for (int i=0;i<mList.size();i++){
            switch (mList.get(i).getName()){
                case "0_sijirenzheng":
                    //司机
                    if (userEntity.getDriverAuthStatus()==1){
                        mList.get(i).setIcon("sijiyirenzheng");
                    }else {
                        mList.get(i).setIcon("sijirenzheng");
                    }
                    break;
                case "0_qiyerenzheng":
                    //企业
                    if (userEntity.isRelevance()){
                        mList.get(i).setIcon("qiyeyirenzheng");
                    }else {
                        mList.get(i).setIcon("qiyerenzheng");
                    }
                    break;
                case "0_tuanduirenzheng":
                    //团队
                    if (userEntity.isTeamAuth()){
                        mList.get(i).setIcon("tuanduiyirenzheng");
                    }else {
                        mList.get(i).setIcon("tuanduirenzheng_no_auth");
                    }
                    break;
                case "0_zuzhirenzheng":
                    //组织
                    if (userEntity.isOrgAuth()){
                        mList.get(i).setIcon("zuzhiyirenzheng");
                    }else {
                        mList.get(i).setIcon("zuzhirenzheng");
                    }
                    break;
            }
        }
        mNoAuthHeadAdapter.clearDatas();
        mNoAuthHeadAdapter.getDatas().addAll(mList);
        mNoAuthHeadAdapter.notifyDataSetChanged();
    }


    @Override
    public void onDestroyView() {
        //EvenBus注销
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    /**
     * 当前用户信息展示及数据处理
     */
    public void displayRole(UserMsgEntity data) {
        this.userEntity = data;
        setLlHeadPersonOrCompany(mType);
        customViewsInfoList.clear();
        //隐藏未登录时界面
        binding.noLoginLl.setVisibility(View.GONE);
        binding.firstordernestingRecyclerview.setVisibility(View.VISIBLE);

        companyNo = data.getCurrentIdentityNo();
        comNo = data.getCurrentIdentityNo();
        mType = data.getType();

        if (mangertype == -1) {
            mangertype = data.getType();
            //mangertype = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, true) ? 1 : 0);
        }

        //实名认证
        mPersonAuth = data.getPersonalAuth() == 1 ? true : false;

        refreshPermissionMenu();

        //判断实名认证
        if (mPersonAuth) {
            //已实名认证
            binding.realNameAuthentication.setImageResource(R.drawable.icon_identity_registered);
            if (mType != 0) {
                binding.tvUserName.setVisibility(View.VISIBLE);
            } else {
                binding.tvUserName.setVisibility(View.GONE);
            }
            binding.identificationLayout.setVisibility(View.GONE);
            binding.nsNoAuth.setVisibility(View.GONE);
            binding.tvUserPhone.setVisibility(View.VISIBLE);
        } else {
            //customViewsInfoList.add(new CustomViewsInfo("实名认证"));
            //未实名认证
            binding.realNameAuthentication.setImageResource(R.drawable.icon_identity_unregistered);
//            if (mType != 0) {
//                binding.tvUserName.setVisibility(View.VISIBLE);
//            }
            binding.tvUserName.setVisibility(View.GONE);
            binding.tvUserPhone.setVisibility(View.GONE);
            binding.identificationLayout.setVisibility(View.VISIBLE);
            binding.nsNoAuth.setVisibility(View.VISIBLE);
            binding.goIdentification.setOnClickListener(this);
        }
        //根据判断身份类型刷新底部菜单“我的”的展示图标及名称
        switch (data.getType()) {
            case 0: //个人
                if (mPersonAuth) {
                    String realName = data.getRealName();
                    if (!TextUtils.isEmpty(realName) && realName.length() > 4) {
                        realName = realName.substring(0, 4);
                    }
                    activity.upDataMyTabIcom(realName, data.getHeadImg());
                } else {
                    activity.upDataMyTabIcom("未实名", R.mipmap.app_tab_self_name_on);
                }
                break;
            case 1: //企业
                String companyName = data.getCompanyName();
                if (!TextUtils.isEmpty(companyName) && companyName.length() > 4) {
                    companyName = companyName.substring(0, 4);
                }
                if (TextUtils.isEmpty(data.getCompanyImage())) {
                    activity.upDataMyTabIcom(companyName, R.mipmap.icon_default_company_self);
                } else {
                    activity.upDataMyTabIcom(companyName, data.getCompanyImage());
                }
                break;
            case 2: //团队
                String teamName = data.getTeamName();
                if (!TextUtils.isEmpty(teamName) && teamName.length() > 4) {
                    teamName = teamName.substring(0, 4);
                }
                if (TextUtils.isEmpty(data.getTeamImage())) {
                    activity.upDataMyTabIcom(teamName, R.mipmap.icon_team_default_1);
                } else {
                    activity.upDataMyTabIcom(teamName, data.getTeamImage());
                }
                break;
            case 3: //组织
                String organizationName = data.getOrganizationName();
                if (!TextUtils.isEmpty(organizationName) && organizationName.length() > 4) {
                    organizationName = organizationName.substring(0, 4);
                }
                if (TextUtils.isEmpty(data.getOrganizationImage())) {
                    activity.upDataMyTabIcom(organizationName, R.drawable.icon_organization_default);
                } else {
                    activity.upDataMyTabIcom(organizationName, data.getOrganizationImage());
                }
                break;
        }

        //未认证切换到个人身份显示手机号
        if (data.getType() == 0 && !mPersonAuth) {
            String phone = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "");
            binding.companyName1.setText(phone);//未认证 显示手机号
        } else {
            binding.companyName1.setText(data.getCurrentIdentityName());
        }
        //显示主公司的名字
        binding.companyName.setText(data.getCurrentIdentityName());
//        viewModel.getCompanyList(false);
        setHeadImg(data.getCurrentIdentityLogo(), data.getType());
        String realName = data.getRealName();
        //判断是否为空
        if (!TextUtils.isEmpty(realName)) {
            if (mType == 0) {
                binding.tvUserName.setVisibility(View.GONE);
                binding.companyName.setText(data.getCurrentIdentityName());
                binding.companyName1.setText(realName);
            } else {
                binding.tvUserName.setVisibility(View.VISIBLE);
            }
            binding.tvUserName.setText(realName);
            setLlHeadPersonOrCompany(mType);
        }
        //初始化网站入口样式
        initWebsiteView();
        //获取基本信息中的手机号码
        String telephone = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LOGIN_PHONE, "");
        //判断是否为空
        if (!TextUtils.isEmpty(telephone)) {
            binding.tvUserPhone.setText(telephone);
        }
        UserEntity.setRealName(realName);
        UserEntity.setImage(data.getCurrentIdentityLogo());
        selfPopWindow.getPersonalPortrait(UserEntity, data.getType());

        if (mIsH5Login) {
            EventBus.getDefault().postSticky(LoginEvent.make(EventConstant.EVENT_REFRESH_WEBSITEINFO, ""));
            mIsH5Login = false;
        }

        //获取用户的基本信息
        viewModel.getEssentialInformation(data.getCurrentIdentityNo(), data.getType());
    }

    /**
     * 显示公司列表
     *
     * @param data
     */
    public void showCompanyList(List<CompanyEntity> data) {
        this.companyList = data;
        //判断是否存在（以前的公共接口，无公司也返回一个空公司，暂时用公司名判断是否存在）
        if (data.size() > 0 && !TextUtils.isEmpty(data.get(0).getCompName())) {
           /* if (isLoginJump) {
                //第一次登陆进来设置为第一个公司的信息
                binding.companyName.setText(data.get(0).getCompName());
                binding.companyName1.setText(data.get(0).getCompName());
                if (data.size() > 1) {
                    if (data.get(0).getType() == 1) {
                        setHeadImg(data.get(0).getCompLogo(), 1);
                    } else if (data.get(0).getType() == 2) {
                        setHeadImg(data.get(0).getCompLogo(), 2);
                    }
                }
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMP_LOGO, data.get(0).getCompLogo());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMPANY_NO, data.get(0).getCompNo());
                IMUtils.getInstance().saveUserCurrentCompanyNo(data.get(0).getCompNo());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMPANY_NAME, data.get(0).getCompName());
                if (!TextUtils.isEmpty(data.get(0).getCompLogo())) {
                    UserEntity.setImage(data.get(0).getCompLogo());
                }
                UserEntity.setRealName(data.get(0).getName());//获取用户在企业的真实姓名
                selfPopWindow.getPersonalPortrait(UserEntity, data.get(0).getType());
                if (SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                    viewModel.getPermissionMenu(data.get(0));//首次进来 默认主企业是第一个 请求权限
                } else { //未认证 单独加接口
                    viewModel.getNoAuthPermissionMenu(data.get(0));
                }
                isLoginJump = false;
            }*/
            //展示公司的弹窗
            binding.companyLayout.setVisibility(View.VISIBLE);
            binding.companyLayout1.setVisibility(View.VISIBLE);
            //如果只有一个公司时，将向上或向下的图标隐藏
            if (data.size() == 1) {
                binding.companyDown.setVisibility(View.GONE);
            }//如果不止一个公司时，将向上或向下的图标显示
            else {
                binding.companyDown.setVisibility(View.VISIBLE);
            }
        } else {
            //如果没有公司则隐藏公司列表
            binding.companyLayout.setVisibility(View.GONE);
            binding.companyLayout1.setVisibility(View.GONE);
        }
    }

    /**
     * 设置展示主企业的基本信息
     *
     * @param company
     */
    public void setCurrentCompany(CompanyEntity company) {
        //未认证切换到个人身份显示手机号
        if (company.getType() == 0 && !SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
            String phone = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "");
            binding.companyName1.setText(phone);//未认证 显示手机号
        } else {
            binding.companyName1.setText(company.getCompName());
        }
        //显示主公司的名字
        binding.companyName.setText(company.getCompName());
//        viewModel.getCompanyList(false);
        setHeadImg(company.getCompLogo(), company.getType());
        String realName = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME, "");
        mType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        //判断是否为空
        if (!TextUtils.isEmpty(realName)) {
            if (mType == 0) {
                binding.tvUserName.setVisibility(View.GONE);
                binding.companyName.setText(company.getCompName());
                binding.companyName1.setText(realName);
            } else {
                binding.tvUserName.setVisibility(View.VISIBLE);
            }
            binding.tvUserName.setText(realName);
            setLlHeadPersonOrCompany(mType);
        }
        //初始化网站入口样式
        initWebsiteView();
        //获取基本信息中的手机号码
        String telephone = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LOGIN_PHONE, "");
        //判断是否为空
        if (!TextUtils.isEmpty(telephone)) {
            binding.tvUserPhone.setText(telephone);
        }
        UserEntity.setRealName(realName);
        UserEntity.setImage(company.getCompLogo());
        selfPopWindow.getPersonalPortrait(UserEntity, company.getType());
        String no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");


    }

    /**
     * 初始化网站入口样式
     */
    private void initWebsiteView() {
        if (mPersonAuth) {
            binding.companyDown.setVisibility(View.VISIBLE);
            binding.companyDown1.setVisibility(View.VISIBLE);
            if (mType != 0) {
                binding.tvUserName.setVisibility(View.VISIBLE);
            }
            binding.tvUserPhone.setVisibility(View.VISIBLE);
            if (mType == 0) {
                //显示个人网站入口
                //binding.tvSiteEntrance.setText("个人网站");
                binding.tvSiteEntrance.setVisibility(View.VISIBLE);
            } else if (mType == 1) {
                //显示企业网站入口
                ///binding.tvSiteEntrance.setText("企业网站");
                binding.tvSiteEntrance.setVisibility(View.VISIBLE);
            } else if (mType == 2) {
                //显示团队网站入口
                //binding.tvSiteEntrance.setText("团队网站");
                binding.tvSiteEntrance.setVisibility(View.VISIBLE);
            } else {
                //显示组织网站入口
                //binding.tvSiteEntrance.setText("组织网站");
                binding.tvSiteEntrance.setVisibility(View.VISIBLE);
            }
            binding.tvSiteEntrance.setText("网站");
        } else {
            binding.companyDown.setVisibility(View.GONE);
            binding.companyDown1.setVisibility(View.GONE);
            //个人未认证 隐藏
            binding.tvSiteEntrance.setVisibility(View.GONE);
            binding.tvUserName.setVisibility(View.GONE);
            binding.tvUserPhone.setVisibility(View.GONE);
        }
    }

    /**
     * 展开客服弹窗
     */

    private void showDialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        //roundCornerDialog.setOnKeyListener(keylistener);//设置点击返回键Dialog不消失
        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        tv_title.setText("联系客服");
        tv_title.setVisibility(View.VISIBLE);
        tv_message.setText("400-001-0051");
        tv_logout_confirm.setText("拨打");
        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + "4000010051");
                intent.setData(data);
                startActivity(intent);
            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭弹窗
                roundCornerDialog.dismiss();
            }
        });
    }

    //Glide展示图片，如果没有用户头像则显示默认头像

    /**
     * 设置团队类型
     *
     * @param entity
     */
    public void showHeadPortrait(EssentiaIinformationeEntity entity) {
        if (!TextUtils.isEmpty(entity.getBusiness())) {
            binding.tvBusinessType.setVisibility(View.VISIBLE);
            binding.tvBusinessType.setText(entity.getBusiness());
        } else {
            binding.tvBusinessType.setVisibility(View.GONE);
        }
    }

    public void setHeadImg(String url, int type) {
        if (!TextUtils.isEmpty(url)) {
            if (type == 1) {
                //Glide展示图片
                Glide.with(this)
                        //加载设置宽高限制
                        .load(url + "?x-oss-process=image/resize,m_fixed,h_250")
                        //显示圆图
                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                        //设置为头像
                        .into(binding.companyLogoIv);
            } else {
                //Glide展示图片
                Glide.with(this)
                        //加载设置宽高限制
                        .load(url + "?x-oss-process=image/resize,m_fixed,h_250")
                        //显示圆图
                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                        //设置为头像
                        .into(binding.companyLogoIv);
            }

        } else {
            ////Glide展示图片，如果没有用户头像则显示默认头像
            if (type == 0) {
                binding.companyLogoIv.setImageResource(R.mipmap.def_photo);
            } else if (type == 1) {
                Glide.with(this)
                        .load(R.mipmap.shop_img_new_2)
                        .apply(new RequestOptions().transform(new CircleCrop()))
                        .into(binding.companyLogoIv);
            } else if (type == 2) {
                binding.companyLogoIv.setImageResource(R.drawable.icon_team_default);
            } else {
                binding.companyLogoIv.setImageResource(R.drawable.icon_organization_default);
            }
        }
    }

    //data为0 回复加载状态
    public void resetMenu() {
        binding.menuRecyclerview.setVisibility(View.GONE);
        binding.firstordernestingRecyclerview.setVisibility(View.GONE);
        binding.longimg.setVisibility(View.VISIBLE);
        binding.longimgs.setVisibility(View.GONE);
        binding.ivNullMenu.setVisibility(View.VISIBLE);
    }


    /**
     * 展示公司权限菜单列表RecyclerTabLayout
     *
     * @param data
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void showPermissionMenu(List<PermissionMenuEntity> data) {
        isEnableClick = true;
        binding.smartRefreshLayout.finishRefresh();//刷新结束
        binding.longimg.setVisibility(View.GONE);
        binding.longimgs.setVisibility(View.GONE);
        binding.smartRefreshLayout.setVisibility(View.VISIBLE);
        dataList.clear();
        //lastPosition = -1;
        //是否展示footer
        isShowFooter(mType, true);
        isShowHeader(true);
        mTabPosition = -1;
        listHeadCompany.clear();
        //binding.tablayout.setVisibility(View.VISIBLE);
        if (data.size() == 0) {
            resetMenu();
        } else {
            //for循环
            //企业目录下无 常用功能 菜单
            //本地移除常用功能菜单了
            //String no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
            //if (!no.equals("0")) {
            //data.remove(0);
            // if (data.size() == 0) {
            //resetMenu();
            //return;
            //}
            //} else {
            binding.firstordernestingRecyclerview.setVisibility(View.VISIBLE);
            binding.menuRecyclerview.setVisibility(View.VISIBLE);
            binding.longimg.setVisibility(View.GONE);
            binding.longimgs.setVisibility(View.GONE);
            binding.ivNullMenu.setVisibility(View.GONE);
            mMenus.clear();
            mAgentCentralizedMiningMenus.clear();
            //}
            //binding.tablayout.setVisibility(data.size() > 4 ? View.VISIBLE : View.GONE);//大于4个显示tab
            if (mType == 1 || mType == 0) { //获取未读数量
                viewModel.getTotalUnReadMsg(false);
            } else {
                getPermissionMenus(data);
            }
            //判断对应的二级list集合是否为空
            //if (data.get(i).getList() != null && data.get(i).getList().size() != 0) {
            //为空则删除dataList.add(data.get(i));
            //}
            dataList.addAll(data);
            //PermissionMenuEntity permissionMenuEntity = new PermissionMenuEntity();
            //permissionMenuEntity.setTitle("全部");
            //dataList.add(0, permissionMenuEntity);
//            binding.tablayout.clearOnTabSelectedListeners();
//            binding.tablayout.removeAllTabs();
//            for (int i = 0; i < dataList.size(); i++) {
//                TabLayout.Tab tab = binding.tablayout.newTab();
//                tab.setText(dataList.get(i).getTitle());
//                binding.tablayout.addTab(tab);
//                if (i == 0) {
//                    tab.select();
//                }
//            }
//            binding.tablayout.scrollTo(0, 0);
//            initTabLayoutTabOnclick();
            dataList.get(0).setChoose(true);
            setMenuRecycleView(dataList);
            //dataList.remove(0);
            //设置数据
            if (!dataList.isEmpty()) {
                reallyDataList.clear();
                reallyDataList.addAll(dataList.get(0).getList()); //默认加载第一条
            }
            binding.hzvScrollview.scrollTo(0, 0);
            firstOrderNestingAdapter.setListData(reallyDataList, companyList, mType);
            setCanNsEnable(0);
        }
        //if (mType == 1) { //企业
        //mMenus.clear();
        //mApplyMenus.clear();
        goToPayEnable = false;
        //viewModel.getOrderMenus(data);
        //}
        String no;
        if (mangertype != 0) {
            no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        } else {
            no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        }
        viewModel.GetToplist(1, no, mangertype);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void setMenuRecycleView(List<PermissionMenuEntity> dataList) {
        ViewGroup.LayoutParams layoutParams = binding.menuRecyclerview.getLayoutParams();
        int colums = 0;
        if (dataList.size() <= 12) {
            binding.menuRecyclerview.setLayoutManager(new GridLayoutManager(getContext(), 6));
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            binding.llIndicator.setVisibility(View.GONE);
        } else {
            if (dataList.size() % 2 != 0) {
                colums = dataList.size() / 2 + 1;
            } else {
                colums = dataList.size() / 2;
            }
            binding.menuRecyclerview.setLayoutManager(new GridLayoutManager(getContext(), colums));
            layoutParams.width = ((SizeUtils.getScreenWidth(getContext()) - SizeUtils.dp2px(94)) / 6) * colums;
            binding.llIndicator.setVisibility(View.VISIBLE);
            binding.menuRecyclerview.post(new Runnable() {
                @Override
                public void run() {
                    binding.treeIndicator.bindHorizontalScrollView(binding.hzvScrollview, getActivity(), binding.menuRecyclerview.getMeasuredWidth() + SizeUtils.dp2px(40));
                }
            });
        }
        if (dataList.size() <= 6) {
            binding.paixu1.setVisibility(View.VISIBLE);
            binding.paixu.setVisibility(View.GONE);
            binding.paixu2.setVisibility(View.GONE);
        } else if (dataList.size() > 6 && dataList.size() < 12) {
            binding.paixu1.setVisibility(View.GONE);
            binding.paixu.setVisibility(View.GONE);
            binding.paixu2.setVisibility(View.VISIBLE);
        } else {
            binding.paixu1.setVisibility(View.GONE);
            binding.paixu.setVisibility(View.VISIBLE);
            binding.paixu2.setVisibility(View.GONE);
        }
        //binding.menuRecyclerview.setLayoutParams(layoutParams);
        if (dataList != null && dataList.size() > 1 && dataList.get(0).getTitle().equals("首页")) { //本地暂时修改
            dataList.get(0).setTitle("首页推荐");
        }
        mMenuAdapter.setNewData(dataList);

    }

    private void getPermissionMenus(List<PermissionMenuEntity> data) {
        UserPermissionUtils.getInstance().getPermission(data, new BasePermissionCallBack() {
            //代办集采
            @Override
            public void getCentralizedMiningPermission(List<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>> centralizedMiningMenus) {
                mTempAgentCentralizedMiningMenus.clear();
                mTempAgentCentralizedMiningMenus.addAll(centralizedMiningMenus);
            }

            //企业 头部代办区域申请权限
            @Override
            public void getCheckPermission(List<PickFilterEntity<Object>> checkMenus) {
                mApplyMenus.clear();
                mApplyMenus.addAll(checkMenus);
                mStaffCheckMenus.clear();
                mCustomerCheckMenus.clear();
                if (!data.isEmpty()) {
                    for (PickFilterEntity entity : checkMenus) {
                        if ("9".equals(entity.getNo())) {//员工审核
                            mStaffCheckMenus.add(entity);
                        } else if ("10".equals(entity.getNo())) {//会员审核
                            mCustomerCheckMenus.add(entity);
                        }
                    }
                }
            }

            //企业 头部代办区域付款权限
            @Override
            public void getPayPermission(List<PickFilterEntity<Object>> payMenus) {
                goToPayEnable = payMenus != null && !payMenus.isEmpty();
            }

            //企业 头部代办区域订单权限
            @Override
            public void getOrderPermission(List<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>> orderMenus) {
                mTempMenus.clear();
                mTempMenus.addAll(orderMenus);
            }

            //代办商品函询
            @Override
            public void getShopEnquiryPermission(List<PickFilterEntity<Object>> shopEnquiryMenus) {
                permissionEnquiryShop = shopEnquiryMenus != null && !shopEnquiryMenus.isEmpty();
            }
        });
    }

    //企业 头部代办区域订单权限
    public void getOrderMenus(List<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>> data) {
        mMenus.clear();
        mMenus.addAll(data);
    }

    //企业 头部代办区域付款权限
    public void getPayMenus(ArrayList<PickFilterEntity<Object>> data) {
        goToPayEnable = data != null && !data.isEmpty();
    }

    //企业 头部代办区域申请权限
    public void getApplyMenus(ArrayList<PickFilterEntity<Object>> data) {
        mApplyMenus.clear();
        mApplyMenus.addAll(data);
        mStaffCheckMenus.clear();
        mCustomerCheckMenus.clear();
        if (!data.isEmpty()) {
            for (PickFilterEntity entity : data) {
                if ("9".equals(entity.getNo())) {//员工审核
                    mStaffCheckMenus.add(entity);
                } else if ("10".equals(entity.getNo())) {//会员审核
                    mCustomerCheckMenus.add(entity);
                }
            }
        }
    }

    //代办集采
    public void getCentralizedMiningMenus(List<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>> data) {
        mAgentCentralizedMiningMenus.clear();
        mAgentCentralizedMiningMenus.addAll(data);
    }

    public void getShopEnquiry(ArrayList<PickFilterEntity<Object>> data) {
        permissionEnquiryShop = data != null && !data.isEmpty();
    }

    private void initTabLayoutTabOnclick() {
        binding.tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                //mTabPosition = position;
                //tipPosition(position);
                if (position < dataList.size()) {
                    reallyDataList.clear();
                    if (dataList.get(position) != null && dataList.get(position).getList() != null && !dataList.get(position).getList().isEmpty()) {
                        reallyDataList.addAll(dataList.get(position).getList());
                    }
                    tipPosition(0);
                    firstOrderNestingAdapter.setDatas(reallyDataList);
                    setCanNsEnable(position);
                }
                isShowFooter(mType, position == 0);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        /*for (int i = 0; i < binding.tablayout.getTabCount(); i++) {
            TabLayout.Tab tab = binding.tablayout.getTabAt(i);
            //这里使用到反射，拿到Tab对象后获取Class
            //c.getDeclaredField 获取私有属性。
            //“view”是Tab的私有属性名称，类型是 TabView ，TabLayout私有内部类。
            Class<? extends TabLayout.Tab> tabClass = tab.getClass();
            try {
                Field field = tabClass.getDeclaredField("view");
                field.setAccessible(true);
                final View view = (View) field.get(tab);
                view.setTag(i);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }*/
    }

    private void getHeight() { //兼容滑动距离
        View decorView = getActivity().getWindow().getDecorView();

        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                decorView.getWindowVisibleDisplayFrame(r);
                int height = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
                int diff = height - r.bottom;
                if (diff != 0) {
                    mChangeHeight = ImmersionBar.getStatusBarHeight(requireActivity());
                } else {
                    mChangeHeight = 0;
                }
            }
        });
    }

    //rv是否可以联动折叠布局
    private void setCanNsEnable(int position) {
        if (position != 0) {
            if (mFooterBinding != null) {
                ViewGroup.LayoutParams lp = binding.firstordernestingRecyclerview.getLayoutParams();
                lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                binding.firstordernestingRecyclerview.setLayoutParams(lp);
            }
        }
        binding.firstordernestingRecyclerview.post(new Runnable() {
            @Override
            public void run() {
                int screenHeight = SizeUtils.getScreenHeight(getContext());
                if (Build.BRAND.equals("vivo")) {//vivo手机
                    screenHeight = screenHeight - mChangeHeight;
                }
                if (binding.llIndicator.getVisibility() == View.VISIBLE) {
                    screenHeight = screenHeight - binding.llIndicator.getMeasuredHeight();
                }
                boolean mCurrentNsEnable = binding.firstordernestingRecyclerview
                        .getMeasuredHeight() + binding.hzvScrollview.getMeasuredHeight() + binding.appBar.getMeasuredHeight() >
                        screenHeight;
                binding.firstordernestingRecyclerview.setNestedScrollingEnabled(mCurrentNsEnable || !SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false));
                if (!isExpanded && !mCurrentNsEnable) {
                    binding.appBar.setExpanded(true);
                }
                if (mCurrentNsEnable) {
                    ViewGroup.LayoutParams lp = binding.firstordernestingRecyclerview.getLayoutParams();
                    lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
                    binding.firstordernestingRecyclerview.setLayoutParams(lp);
                }
            }
        });
    }

    /**
     * 初始化数据列表展示
     */
    private void initRecyclerview() {
        binding.appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                binding.smartRefreshLayout.setEnabled(i >= 0);
            }
        });
        binding.firstordernestingRecyclerview.setVisibility(View.VISIBLE);
        binding.ivNullMenu.setVisibility(View.GONE);
        if (firstOrderNestingAdapter == null) {
            //创建第一级的适配器
            firstOrderNestingAdapter = new SelfFirstOrderNestingAdapter(getActivity(), new ArrayList<>(), companyList, mType);
            //Recyclerview设置布局管理器
            binding.firstordernestingRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
            //设置项目视图缓存大小为100(防止卡顿)
            binding.firstordernestingRecyclerview.setItemViewCacheSize(100);
            //recycleView设置适配器
            binding.firstordernestingRecyclerview.setAdapter(firstOrderNestingAdapter);
//            firstOrderNestingAdapter.getMutableLiveData().observe(this, new Observer<Map<String, String>>() {
//                @Override
//                public void onChanged(Map<String, String> map) {
//                    goToSwitchTo(map);
//                }
//            });
            firstOrderNestingAdapter.setOnClickMorelistener(new SelfFirstOrderNestingAdapter.ClickMorelistener() {
                @Override
                public void onClickMorelistener() {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), SecondMoreActivity.class);
                    intent.putExtra("list", (Serializable) dataList.get(0).getList().get(0).getList());
                    intent.putExtra("mangertype", mangertype);
                    startActivityForResult(intent, SECONDMORE);
                }
            });
        }
        MineAdapterItemClick.getInstance().setOnOnUrlMapDataCallBacklistener(new MineAdapterItemClick.UrlMapDataCallBack() {
            @Override
            public void OnUrlMapDataCallBacklistener(Map<String, String> map, String from) {
                      goToSwitchTo(map);
            }
        });
        //recycleView添加滑动事件
//        binding.firstordernestingRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(@NonNull final RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                //获得recyclerView的线性布局管理器
//                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
//                //获取到第一个item的显示的下标  不等于0表示第一个item处于不可见状态 说明列表没有滑动到顶部 显示回到顶部按钮
//                int firstVisibleItemPosition = manager.findFirstVisibleItemPosition();
//                // 当不滚动时
//                isRecyclerViewScroll = true;
//                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    if (firstVisibleItemPosition == 0) {
//                        //回到顶部时，置顶按钮隐藏
//                        binding.top.setVisibility(View.GONE);
//                    } else {
//                        // 判断是否滚动超过一屏,置顶按钮显示
//                        binding.top.setVisibility(View.VISIBLE);
//                        //置顶按钮的点击事件
//                        binding.top.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                //置顶按钮隐藏
//                                binding.top.setVisibility(View.GONE);
//                                //打开APPBar的布局
//                                binding.appBar.setExpanded(true);
//                                //停止滑动
//                                recyclerView.stopScroll();
//                                //返回到顶部
//                                recyclerView.scrollToPosition(0);
//                            }
//                        });
//                    }
//                    isRecyclerViewScroll = false;
//                }
//            }
//
//            @Override
//            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
////                try {
////                    int currentPosition = RecyclerViewUtils.findFirstVisiblePosition(recyclerView);
////                    if (lastPosition != currentPosition) {
////                        lastPosition = currentPosition;
////                        //要滑动的时候 去判断点击的tab的位置跟recyclerView的可见位置做比较 取最大的 否则tab到不了指定点击的位置
////                        currentPosition = Math.max(mTabPosition, currentPosition);
////                        binding.tablayout.getTabAt(currentPosition).select();
////                        mTabPosition = -1;//重置下 不然最大值的话 无法滑动
////                    }
////                } catch (Exception e) {
////
////                }
//            }
//        });
        firstOrderNestingAdapter.addFooterView(getDynamicRecycleView());
        firstOrderNestingAdapter.addFooterView(getBusinessOpportunities());
        firstOrderNestingAdapter.addHeaderView(getHeaderView());
    }


    public void setApplyCount(ApplyCount applyCount) {
        if (dataList.size() > 0) {
            PermissionMenuEntity menuEntity = dataList.get(0);
            for (int i = 0; i < menuEntity.getList().size(); i++) {
                PermissionMenuEntity.ListEntity secondEntity = menuEntity.getList().get(i);
                if (secondEntity.getList() != null && !secondEntity.getList().isEmpty()) {
                    for (int j = 0; j < secondEntity.getList().size(); j++) {
                        PermissionMenuEntity.ListEntity listEntity = secondEntity.getList().get(j);
                        switch (j) {
                            case 0:
                                listEntity.setCount(applyCount.getNeedOfNum());
                                break;
                            case 1:
                                listEntity.setCount(applyCount.getLaunchMeNum());
                                break;
                            case 2:
                                listEntity.setCount(applyCount.getFinishedNum());
                                break;
                            case 3:
                                listEntity.setCount(applyCount.getNotifyNum());
                                break;
                        }
                    }
                }
            }
        }
        firstOrderNestingAdapter.notifyDataSetChanged();
    }

    /**
     * 根据观察点击事件响应跳转
     *
     * @param map
     */
    private void goToSwitchTo(Map<String, String> map) {
        viewModel.getStringUrl(map);
    }

    /**
     * 动画的实施步骤
     */

    @SuppressLint("NewApi")
    private ValueAnimator createDropAnim(final String type, final View view, int start, int end) {
        ValueAnimator va = ValueAnimator.ofInt(start, end);
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (Integer) animation.getAnimatedValue();
                //动态设置高度
                ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                layoutParams.height = value;
                view.setLayoutParams(layoutParams);
                //如果是关闭动画，当动画结束时view设置为GONE
                if (type.equals("close")) {
                    if (value == 0) {
                        view.setVisibility(View.GONE);
                    }
                }
            }
        });
        return va;
    }

    private void checkPermission() {
        if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            activity.jumpLogin();
            return;
        }
        if (PermissionsUtil.hasPermission(getActivity(), Manifest.permission.CAMERA)) {
            ScanActivity.start(getActivity());
        } else {
            PermissionsUtil.requestPermission(getActivity(), new PermissionListener() {
                @Override
                public void permissionGranted(@NonNull String[] permissions) {
                    ScanActivity.start(getActivity());
                }

                @Override
                public void permissionDenied(@NonNull String[] permissions) {
                    MToast.showLongToast(getActivity(), "请先获取相机权限");
                }
            }, Manifest.permission.CAMERA);
        }
    }

    private void optState() {
        new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                .setTitle("提示")
                .setMsg("你还没有完成实名认证,请先完成个人实名认证再进行其他认证")
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        CertificationActivity.start(getActivity(), "1");
                    }

                    @Override
                    public void onLeftClick() {

                    }
                }).show();
    }


    // TODO: 2021/5/13 0013 资金中心1.4.0
    public void getProcess(CapitalEntity data) {
        mProcess = data.process;
    }

    @Subscribe
    public void getCode(MessageEvent event) {
        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        mIsUser = type == 0;
        switch (event.code) {
            case EventConstant.EVENT_ZHANGWULIUSHUI:
                FinanceFlowAndCostQueryActivity.start(getActivity(), mIsUser, 0);
                break;
            case EventConstant.EVENT_ZHANGDAN:
                BusinessManagementActivity.start(getActivity(), (Integer) event.data);
                break;
            case EventConstant.EVENT_KAIPIAOJILU:
                AsiaRecordActivity.start(getActivity());
                break;
            case EventConstant.EVENT_YUECHONGZHI:
                if (showPop(event, 2, 1)) return;
                PayActivity.start(getActivity(), false, mIsUser);
                break;
            case EventConstant.EVENT_TUIKUANLIEBIAO:
                if (showPop(event, 2, 1)) return;
                ReimburseActivity.start(getActivity());
                break;
            case Constants.EVENT_REFRESH_TIP:
                mProcess = 1;
                break;
            case EventConstant.EVENT_ZAIXIANZHUANZHUANG:
                if (showPop(event, 2, 1)) return;
                TransferAccountsActivity.start(getActivity());
                break;
            case EventConstant.EVENT_FEIYONGCHAXUN:
                FinanceFlowAndCostQueryActivity.start(getActivity(), mIsUser, 1);
                break;
            case EventConstant.EVENT_ZHANGHUMINGXI:
                if (showPop(event, 2, 1)) return;
                AccountActivity.start(getActivity());
                break;
            case EventConstant.EVENT_RENZHENGZILIAO:
                if (showPop(event, 2, 1)) return;
                if (mIsUser) {
                    CertificatedUserActivity.start(getActivity());
                } else {
                    CertificatedCompanyActivity.start(getActivity());
                }
                break;
            case EventConstant.EVENT_YINHANGKA:
                mBank.data = mProcess + "";
                if (mIsUser) {
                    PersonBankCardsActivity.start(getActivity());
                } else {
                    CompanyBankCardsActivity.start(getActivity(), mProcess);
                }
                break;
            case EventConstant.EVENT_YUETIXIAN:
                if (showPop(event, 1, 2)) return;
                if (mProcess == 2) {
                    TipPop bind = new TipPop(getActivity(), "温馨提示", "暂未绑定提现银行卡，请及时绑定", "立即绑卡", "知道了");
                    bind.show();
                    bind.mTvSure.setOnClickListener(v -> {
                                bind.dismiss();
                                if (mIsUser) {
                                    PersonBankCardsActivity.start(getActivity());
                                } else {
                                    CompanyBankCardsActivity.start(getActivity(), mProcess);
                                }
                            }
                    );
                    return;
                }
                WithdrawalBalanceActivity.start(getActivity(), mIsUser);
                break;
            case EventConstant.EVENT_DAIFUDINGDAN:
                BusinessManagementActivity.start(getActivity(), 1);
                break;
            case EventConstant.KAI_HU_ZI_LIAO:
                viewModel.getCompanyDetail(getActivity(), 2, mIsUser);
                break;
            case EventConstant.HE_TONG_LIE_BIAO:
                viewModel.getCompanyDetail(getContext(), 1, mIsUser);
                break;
            case Constants.EVENT_REFRESH_DATA:
                getData();
                break;
        }
    }

    private boolean showPop(MessageEvent event, int i, int i2) {
        if (mProcess == 0 || mProcess == 3 || mProcess == 1) {
            TipPop tipPop = new TipPop(getActivity(), "温馨提示",
                    mProcess == 1 ? ("企业钱包开通审核中\n通过后可使用此功能") : (mIsUser ? "开通个人钱包后\n" : "开通企业钱包后\n") +
                            "可使用此功能", (mProcess == i || mProcess == i2) ? null : "前往开通", "知道了");
            tipPop.show();
            tipPop.mTvSure.setOnClickListener(v -> {
                tipPop.dismiss();
                OpenAccountFirstActivity.start(getActivity(), mIsUser);
            });
            return true;
        }
        return false;
    }

    /**
     * 获取企业头部区域未读数量
     * isRefreshNum 刷新代办集采和询价的数量
     *
     * @param data
     */
    public void getTotalUnReadMsg(TotalUnReadMsgEntity data, boolean isRefreshNum) {
        getPermissionMenus(dataList);
        if (mType == 1 || mType == 0) {
            List<PermissionMenuEntity.ListEntity> datas = mHeadCompanyAdapter.getDatas();
            if (datas != null && !datas.isEmpty()) {
                if (!isRefreshNum) {
                    for (PermissionMenuEntity.ListEntity entity : datas) {
                        if (entity.getName().equals("5_hanxun")) {
                            mInquiryNum = "" + data.getInquiryCount();
                            entity.setCount(data.getInquiryCount());
                        }
//                            else if (mType == 0 && entity.getName().equals("5_hanxun")) {
//                                mInquiryNum = "" + data.getPersonalHanXun();
//                                entity.setCount(data.getPersonalHanXun());
//                            }
                        else if (entity.getName().equals("7_dingdan")) {
                            entity.setCount(viewModel.getTotalOrderNum(data, mTempMenus));
                        } else if (entity.getName().equals("8_fukuan")) {
                            if (goToPayEnable) {
                                entity.setCount(data.getPayCount());
                            }
                        } else if (entity.getName().equals("11_ucshenqing")) {
                            //viewModel.getCheckApply(data.getEmployeeCount(), data.getCustomerCount());
                            entity.setCount(data.getEmployeeCount() + data.getCustomerCount());
                        } else if (entity.getName().equals("24_xinyuangong")) {
                            entity.setCount(data.getEmployeeCount());
                        } else if (entity.getName().equals("24_xinhuiyuan")) {
                            entity.setCount(data.getCustomerCount());
                        } else if (entity.getName().equals("24_xinchengyuan")) {
                            entity.setCount(data.getMemberAuditCount());
                        } else if (entity.getName().equals("1_daiban")) { //待办
                            entity.setCount(data.getDaiBanCount());
                        } else if (entity.getName().equals("10_xunjia")) {
                            entity.setCount(data.getGoodsXunJiaCount());
                        } else if (entity.getName().equals("13_ucjicai")) {
                            viewModel.getJiCaiNum(data.getJiCaiJiaMenCount(), data.getJiCaiBaoJiaCount(), mTempAgentCentralizedMiningMenus);
                            entity.setCount(data.getJiCaiJiaMenCount() + data.getJiCaiBaoJiaCount());
                        }
                    }
                } else {
                    for (PermissionMenuEntity.ListEntity entity : datas) {
                        if (entity.getName().equals("10_xunjia")) {
                            entity.setCount(data.getGoodsXunJiaCount());
                        } else if (entity.getName().equals("13_ucjicai")) {
                            viewModel.getJiCaiNum(data.getJiCaiJiaMenCount(), data.getJiCaiBaoJiaCount(), mTempAgentCentralizedMiningMenus);
                            entity.setCount(data.getJiCaiJiaMenCount() + data.getJiCaiBaoJiaCount());
                        }
                    }
                }
            }
            mHeadCompanyAdapter.notifyDataSetChanged();
        }
    }

    //菜单权限请求失败
    public void dismissRefresh() {
        binding.smartRefreshLayout.finishRefresh();
        isShowFooter(0, true);
    }

    public void sendMsg() {
        EventBus.getDefault().postSticky(EventConstant.EVENT_REFRESH_MAIN);
    }


    class BusinessTypeAdapter extends BaseQuickAdapter<PickFilterEntity, BaseViewHolder> {

        private ItemWebsiteTabFirstBinding mItemBindIng;

        public BusinessTypeAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(BaseViewHolder helper, PickFilterEntity item) {
            mItemBindIng = DataBindingUtil.bind(helper.itemView);
            if (mItemBindIng != null) {
                mItemBindIng.tvTabName.setText(item.getName());
                if (!item.isChoose()) {
                    mItemBindIng.tvTabName.setColors(R.color.color_main_bg, R.color.color_main_bg);
                } else {
                    mItemBindIng.tvTabName.setColors(R.color.color_main_10, R.color.color_main_10);
                }
                mItemBindIng.tvTabName.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.sp12));
                mItemBindIng.tvTabName.setTextColor(getResources().getColor(item.isChoose() ? R.color.color_main : R.color.black));
                RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) mItemBindIng.tvTabName.getLayoutParams();
                lp.topMargin = (int) getResources().getDimension(R.dimen.dp10);
                lp.bottomMargin = (int) getResources().getDimension(R.dimen.dp10);
                lp.leftMargin = (int) getResources().getDimension(R.dimen.dp5);
                lp.rightMargin = (int) getResources().getDimension(R.dimen.dp5);
                mItemBindIng.tvTabName.setPadding(SizeUtils.dp2px(16), SizeUtils.dp2px(6), SizeUtils.dp2px(16), SizeUtils.dp2px(6));
                mItemBindIng.tvTabName.setLayoutParams(lp);

            }
        }
    }

    //菜单
    class SelfMenuAdapter extends BaseQuickAdapter<PermissionMenuEntity, BaseViewHolder> {
        private ItemSelfMenuBinding mItemBinding;
        private ScaleXSpan mScaleXSpan = new ScaleXSpan(1.3f);
        private SpannableString ssb;

        public SelfMenuAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(BaseViewHolder helper, PermissionMenuEntity item) {
            mItemBinding = DataBindingUtil.bind(helper.itemView);
            ssb = new SpannableString(item.getTitle());
            ssb.setSpan(mScaleXSpan, 0, item.getTitle().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            mItemBinding.tvTitle.setText(ssb);
            mItemBinding.tvTitle.setTextColor(getResources().getColor(item.isChoose() ? R.color.color_main : R.color.color_title_big));
            //mItemBinding.line.setVisibility(item.isChoose() ? View.VISIBLE : View.INVISIBLE);
            ViewGroup.LayoutParams lp = mItemBinding.tvTitle.getLayoutParams();
            //lp.width = ((SizeUtils.getScreenWidth(getContext()) - SizeUtils.dp2px(94)) / 8);
            mItemBinding.tvTitle.setLayoutParams(lp);
//           lp = mItemBinding.line.getLayoutParams();
//           if ("首页".equals(item.getTitle())){
//               lp.width = SizeUtils.dp2px(30);
//           } else {
//               lp.width = SizeUtils.dp2px(30);
//           }
//           mItemBinding.line.setLayoutParams(lp);
        }
    }


    @Subscribe
    public void getCode(ZMessageEvent event) {
        switch (event.code) {
            case Constants
                    .EVENT_REFRESH_DATA:
                Utils.postDelay(() -> getData(), 1000);
                break;
        }
    }

}